<?php

namespace app\merchants\services;

use app\common\loader\ModelMerchant;
use app\common\loader\ModelSystem;
use app\common\loader\Services;
use app\common\traits\UploadsOssTrait;
use app\common\traits\WechatTrait;
use think\db\exception\DbException;
use think\Exception;

class SystemService extends BaseService
{
    use UploadsOssTrait, WechatTrait;


    /**
     * 获取商户信息
     * @param string $mer_id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(string $mer_id): array
    {
        $info = ModelMerchant::MerchantInfo()->where('mer_id', $mer_id)
            ->withoutField(['status', 'update_at'])
            ->find();
        if (empty($info)) {
            throw  new Exception('商户信息未找到', API_ERROR);
        }

        // 获取管理员的登录信息
        $userInfo = ModelMerchant::Merchant()->where('id', $info['assoc_manager_id'])
            ->field('open_id,last_login_time,last_login_ip')
            ->find();
        if (!empty($userInfo)) {
            $wxInfo = Services::Helper()->getWechatUserInfo($userInfo['open_id']);
            $userInfo = array_merge($userInfo, $wxInfo);
        } else {
            $userInfo = ['open_id' => '', 'nick_name' => '', 'head_img' => '', 'last_login_time' => '', 'last_login_ip' => ''];
        }
        $entry_url = merchant_entry($mer_id);
        $info = array_merge($info, $userInfo);
        $info['entry'] = $this->makeQrcodeUrl($entry_url);
        $info['entry_url'] = $entry_url;
        $stockInfo = ModelMerchant::MerchantStock()->getStockInfo($mer_id);
        unset($stockInfo['mer_id']);
        $info['stock'] = $stockInfo;
        return $info;
    }

    /**
     *  保存设置
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function saveSetting(string $mer_id, array $param)
    {
        $field = [
            'company_name', 'address', 'contact', 'pic', 'content', 'restrict_location', 'distance', 'phone'
        ];
        $saveData = [];
        foreach ($field as $v) {
            if (isset($param[$v])) {
                $saveData[$v] = $param[$v];
            }
        }
        if (empty($saveData)) {
            return true;
        }
        return ModelMerchant::MerchantInfo()->where('mer_id', $mer_id)->update([], $saveData);
    }

    /**
     * 虚码套餐列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DbException
     */
    public function virtualPackage()
    {
        return ModelSystem::SystemVirtualPackage()->packageList();
    }

    /**
     *  地区列表
     * @param $id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function AreaList($id)
    {
        return ModelSystem::SystemArea()->areaList($id);
    }

    /**
     * 商户管理者绑定微信
     * @throws Exception
     */
    public function merchantAuth(array $params)
    {
//        $mer_status = ModelMerchant::MerchantInfo()->checkMerchantStatus($params['mkey'] ?? '');
//        if (empty($mer_status)) {
//            api_exception(API_ERROR, '商户已被禁用,请联系客服');
//        }

        $userInfo = ModelMerchant::Merchant()->where('id', $params['state'])->field('id,open_id')->find();
        if (empty($userInfo)) {
            api_exception(API_ERROR, '管理员不存在或已删除,请联系客服');
        }

        $wx_openid = $this->wxOauth($params);
        $wx_info = $this->wxInfo($wx_openid);
        return ModelMerchant::Merchant()->removeOption()->where('id', $params['state'])
            ->update([], ['nickname' => $wx_info['nickname'],'head_img' => $wx_info['headimgurl'],'open_id' => $wx_info['openid'], 'union_id' => $wx_info['union_id'] ?? '']);
    }

    /**
     * 获取商户库存信息
     * @param string $merId
     * @return mixed
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function stock(string $merId)
    {
        return ModelMerchant::MerchantStock()->getStockInfo($merId);
    }

    /**
     * 系统日志
     * @param array $options
     * @return mixed
     * @throws Exception
     * @throws DbException
     */
    public function systemLog(array $options)
    {
        $options['order'] = 'id desc';
        $options['without_field'] = 'request';
        return ModelMerchant::MerchantOplog()->page($options);
    }

    /**
     * 系统统计
     * @param $mer_id
     * @return array
     */
    public function sysHome($mer_id): array
    {
        $userInfo = ModelMerchant::MerchantStock()->getUserStatistics($mer_id);
        return [
            'balance' => $userInfo['balance'] ?? 0,
            'virtual_num' => $userInfo['virtual_num'] ?? 0,
            'real_num' => $userInfo['real_num'] ?? 0,
            'product_num' => $userInfo['product_num'] ?? 0,
            'shop_num' => $userInfo['shop_num'] ?? 0,
            'salesman_all_num' => $userInfo['salesman_num']['all_num'] ?? 0,
            'salesman_num' => $userInfo['salesman_num']['sum'] ?? 0,
            'virtual_promo_num' => $userInfo['virtual_promo_num'] ?? 0,
            'order_num' => $userInfo['order_num'] ?? 0
        ];
    }


    public function checkUser(array $where)
    {
        return ModelMerchant::Merchant()->checkUser($where);
    }

    /**
     * 首页商户统计
     * @param $mer_id
     * @return array
     */
    public function sysMerchantHome($mer_id , $date = 'day'): array
    {
        if ((string)$date === 'day'){
            $etime = date("Y-m-d");
            $stime = date("Y-m-d", strtotime('-7 day'));
            $table = 'merchant_statistic_day';
        }

        if ((string)$date === 'month'){
            $etime = date("Y-m");
            $stime = date("Y-m", strtotime('-7 month'));
            $table = 'merchant_statistic_month';
        }

        $where = [['statistics_date', 'between', [$stime, $etime]]];

         $field = 'coalesce(sum(manager_red_packet),0) as re_packet,
         coalesce(sum(manager_point),0) as point,
         coalesce(sum(code_number),0) as code_number,statistics_date as create_at';
        return ModelMerchant::MerchantStatistic()->getStatisticData(
            $table,
            $mer_id,
            $field,
            $where
        );
    }
}
